#!/bin/bash

# sed -i 's/\r$//' app.sh

APP_NAME=$(ls | grep .jar$)
APP_FULL_NAME=$(pwd)/$APP_NAME

if [ -z $APP_NAME ]; then
    echo "Please check that this script and your jar-package is in the same directory!"
    exit 1
fi

# -f kill -9 default kill
KILL_FORCE_FLAG=$2

JAVA_HOME="/opt/java/jdk1.8.0_261"

RUN_ARGS="-jar $APP_FULL_NAME --server.port=8868"

RUN_CMD="$JAVA_HOME/bin/java $RUN_ARGS"

function start() {
    count=$(ps -ef | grep java | grep $APP_FULL_NAME | wc -l)
    if [ $count != 0 ]; then
        echo "Maybe $APP_NAME is running, please check it..."
    else
        echo ">>>>>>> The $APP_NAME is starting... <<<<<<<"

        echo "RUN_CMD :: $RUN_CMD"
        nohup $RUN_CMD >stdout.log &

        echo ">>>>>>> start finish. <<<<<<<"

        tail -200f stdout.log
    fi
}

function stop() {
    appId=$(ps -ef | grep java | grep $APP_FULL_NAME | awk '{print $2}')
    if [ -z $appId ]; then
        echo "Maybe $APP_NAME not running, please check it..."
    else
        echo -n ">>>>>>> The $APP_NAME is stopping... <<<<<<<"

        if [ "$KILL_FORCE_FLAG" == "-f" ]; then
            echo " by force"
            kill -9 $appId
            echo ">>>>>>> stop by force finish. <<<<<<<"
        else
            echo
            kill $appId
            echo ">>>>>>> stop finish. <<<<<<<"
        fi

        sleep 1
        status
    fi
}

function restart() {
    stop
    for i in {3..1}; do
        echo -n "$i "
        sleep 1
    done
    echo 0
    start
}

function status() {
    appId=$(ps -ef | grep java | grep $APP_FULL_NAME | awk '{print $2}')
    if [ -z $appId ]; then
        echo -e "\033[31m Not running \033[0m"
    else
        echo -e "\033[32m Running [$appId] \033[0m"
    fi
}

function logs() {
    tail -200f stdout.log
}

function usage() {
    echo "Usage: $0 {start|stop|restart|status|logs|stop -f}"
    echo "Example: $0 start"
    exit 1
}

case $1 in
start)
    start
    ;;

stop)
    stop
    ;;

restart)
    restart
    ;;

status)
    status
    ;;

logs)
    logs
    ;;

*)
    usage
    ;;
esac
